/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TelaInicial.java
 *
 * Created on 24/10/2011, 22:11:04
 */

package gui;

/**
 *
 * @author Gabriel Queiroz
 */

import java.awt.Color;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import compilador.JCompiler;

public class TelaInicial extends javax.swing.JFrame {

    private Thread compiler;

    /** Creates new form TelaInicial */
    public TelaInicial() {
        initComponents();
        areaCodigo.setBorder(new NumberBorder());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuBar2 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabelaDeSimbolos = new javax.swing.JTable();
        jToolBar1 = new javax.swing.JToolBar();
        botãoSalvar = new javax.swing.JButton();
        botaoCompilar = new javax.swing.JButton();
        abortar = new javax.swing.JButton();
        abrir = new javax.swing.JButton();
        botaoNovo = new javax.swing.JButton();
        botãoLimpar = new javax.swing.JButton();
        botãoAjuda = new javax.swing.JButton();
        tabArquivosTexto = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        areaCodigo = new javax.swing.JTextArea();
        tabTokens = new javax.swing.JTabbedPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        tabSaida = new javax.swing.JTabbedPane();
        jScrollPane4 = new javax.swing.JScrollPane();
        areaSaida = new javax.swing.JTextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        arquivo = new javax.swing.JMenu();
        menuSalvar = new javax.swing.JMenuItem();
        menuAbrir = new javax.swing.JMenuItem();
        menuNovo = new javax.swing.JMenuItem();
        menuAjuda = new javax.swing.JMenuItem();
        compilar = new javax.swing.JMenu();
        compilarLexico = new javax.swing.JMenuItem();
        menuAbortar = new javax.swing.JMenuItem();

        jMenu1.setText("File");
        jMenuBar2.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar2.add(jMenu2);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tabelaDeSimbolos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(tabelaDeSimbolos);

        jToolBar1.setRollover(true);
        jToolBar1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        botãoSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/floppy_disk_48.png"))); // NOI18N
        botãoSalvar.setToolTipText("Salvar");
        botãoSalvar.setFocusable(false);
        botãoSalvar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        botãoSalvar.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/floppy_disk_48.png"))); // NOI18N
        botãoSalvar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        botãoSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botãoSalvarActionPerformed(evt);
            }
        });
        jToolBar1.add(botãoSalvar);

        botaoCompilar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/spanner_48.png"))); // NOI18N
        botaoCompilar.setToolTipText("Compilar");
        botaoCompilar.setFocusable(false);
        botaoCompilar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        botaoCompilar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        botaoCompilar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCompilarActionPerformed(evt);
            }
        });
        jToolBar1.add(botaoCompilar);

        abortar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/cancel_48.png"))); // NOI18N
        abortar.setToolTipText("Abortar");
        abortar.setFocusable(false);
        abortar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        abortar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(abortar);

        abrir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/folder_48.png"))); // NOI18N
        abrir.setToolTipText("Abrir");
        abrir.setFocusable(false);
        abrir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        abrir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        abrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                abrirActionPerformed(evt);
            }
        });
        jToolBar1.add(abrir);

        botaoNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/paper_48.png"))); // NOI18N
        botaoNovo.setToolTipText("Novo");
        botaoNovo.setFocusable(false);
        botaoNovo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        botaoNovo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        botaoNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoNovoActionPerformed(evt);
            }
        });
        jToolBar1.add(botaoNovo);

        botãoLimpar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/refresh_48.png"))); // NOI18N
        botãoLimpar.setToolTipText("Limpar");
        botãoLimpar.setFocusable(false);
        botãoLimpar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        botãoLimpar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        botãoLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botãoLimparActionPerformed(evt);
            }
        });
        jToolBar1.add(botãoLimpar);

        botãoAjuda.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/questionmark_48.png"))); // NOI18N
        botãoAjuda.setToolTipText("Ajuda");
        botãoAjuda.setFocusable(false);
        botãoAjuda.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        botãoAjuda.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(botãoAjuda);

        areaCodigo.setColumns(20);
        areaCodigo.setRows(5);
        jScrollPane1.setViewportView(areaCodigo);

        tabArquivosTexto.addTab("Novo Arquivo", jScrollPane1);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane3.setViewportView(jTable1);

        tabTokens.addTab("Tokens!", jScrollPane3);

        areaSaida.setColumns(20);
        areaSaida.setEditable(false);
        areaSaida.setRows(5);
        jScrollPane4.setViewportView(areaSaida);

        tabSaida.addTab("Saída do compilador", jScrollPane4);

        arquivo.setText("Arquivo");
        arquivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                arquivoActionPerformed(evt);
            }
        });

        menuSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/floppy_disk_48_menor.png"))); // NOI18N
        menuSalvar.setText("Salvar");
        menuSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuSalvarActionPerformed(evt);
            }
        });
        arquivo.add(menuSalvar);

        menuAbrir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/folder_48_menor.png"))); // NOI18N
        menuAbrir.setText("Abrir");
        arquivo.add(menuAbrir);

        menuNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/paper_48_menor.png"))); // NOI18N
        menuNovo.setText("Novo");
        arquivo.add(menuNovo);

        menuAjuda.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/questionmark_48_menor.png"))); // NOI18N
        menuAjuda.setText("Ajuda");
        arquivo.add(menuAjuda);

        jMenuBar1.add(arquivo);

        compilar.setText("Compilar");

        compilarLexico.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/spanner_48_menor.png"))); // NOI18N
        compilarLexico.setText("Compilar Léxico");
        compilarLexico.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                compilarLexicoActionPerformed(evt);
            }
        });
        compilar.add(compilarLexico);

        menuAbortar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/cancel_48_menor.png"))); // NOI18N
        menuAbortar.setText("Abortar");
        compilar.add(menuAbortar);

        jMenuBar1.add(compilar);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(tabSaida, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 971, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(tabTokens, javax.swing.GroupLayout.PREFERRED_SIZE, 367, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tabArquivosTexto, javax.swing.GroupLayout.DEFAULT_SIZE, 598, Short.MAX_VALUE))
                    .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 971, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tabTokens, javax.swing.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE)
                    .addComponent(tabArquivosTexto, javax.swing.GroupLayout.PREFERRED_SIZE, 444, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tabSaida, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botãoSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botãoSalvarActionPerformed
        JFileChooser save = new JFileChooser();
        save.setFileSelectionMode(JFileChooser.FILES_ONLY);
        save.addChoosableFileFilter(new FileNameExtensionFilter("Arquivos texto", "txt", "dat", "java"));

        int a = save.showSaveDialog(null);

        if(a == JFileChooser.APPROVE_OPTION){
            File arquivo = new File(save.getSelectedFile().getAbsolutePath() + ".txt");
            FileWriter file = null;

            try{
                file = new FileWriter(arquivo);
                file.write(areaCodigo.getText()); //modificar parametro
                file.close();
            }catch(IOException e){
                //null
            }
        }//fim do if

        tabArquivosTexto.setTitleAt(0, save.getSelectedFile().getName());

    }//GEN-LAST:event_botãoSalvarActionPerformed

    private void abrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_abrirActionPerformed
        JFileChooser open = new JFileChooser();
        open.setDialogTitle("Abrir Código");
        open.setFileSelectionMode(JFileChooser.FILES_ONLY);
        open.addChoosableFileFilter(new FileNameExtensionFilter("Arquivos textos", "txt", "dat", "java"));

        int a = open.showOpenDialog(null);
        if(a == JFileChooser.APPROVE_OPTION){
            try{

                FileReader reader = new FileReader(open.getSelectedFile());
                BufferedReader buf = new BufferedReader(reader);
                int cont = 1;
                String line = "";
                String aux = "";

                do{
                    try{
                        line = buf.readLine();
                        if(line != null){
                            aux = aux + line;
                            aux = aux + "\n";
                        }
                    }catch(IOException e){
                        Logger.getLogger(TelaInicial.class.getName()).log(Level.SEVERE, null, e);
                    }
                }while(line != null);

                tabArquivosTexto.setTitleAt(0, open.getSelectedFile().getName());
                areaCodigo.setText(aux);

            }catch(FileNotFoundException f){
                Logger.getLogger(TelaInicial.class.getName()).log(Level.SEVERE, null, f);

            }
        }
    }//GEN-LAST:event_abrirActionPerformed

    private void menuSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuSalvarActionPerformed
        JFileChooser save = new JFileChooser();
        save.setFileSelectionMode(JFileChooser.FILES_ONLY);
        save.addChoosableFileFilter(new FileNameExtensionFilter("Arquivos texto", "txt", "dat", "java"));

        int a = save.showSaveDialog(null);

        if(a == JFileChooser.APPROVE_OPTION){
            File arquivo = new File(save.getSelectedFile().getAbsolutePath() + ".txt");
            FileWriter file = null;

            try{
                file = new FileWriter(arquivo);
                file.write(areaCodigo.getText()); //modificar parametro
                file.close();
            }catch(IOException e){
                //null
            }
        }//fim do if

        tabArquivosTexto.setTitleAt(0, save.getSelectedFile().getName());
    }//GEN-LAST:event_menuSalvarActionPerformed

    private void botaoCompilarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCompilarActionPerformed
        if(this.areaCodigo.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Não há código para compilar!");
        }

        this.botãoLimparActionPerformed(evt);
        
        JCompiler j = new JCompiler(this, this.areaCodigo.getText());

        compiler = new Thread(j);
        compiler.start();

    }//GEN-LAST:event_botaoCompilarActionPerformed

    private void compilarLexicoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_compilarLexicoActionPerformed
        if(this.areaCodigo.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Não há código para compilar!");
        }

        this.botãoLimparActionPerformed(evt);

        JCompiler j = new JCompiler(this, this.areaCodigo.getText());

        compiler = new Thread(j);
        compiler.start();
    }//GEN-LAST:event_compilarLexicoActionPerformed

    private void botãoLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botãoLimparActionPerformed

        this.areaSaida.setText("");
        this.jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{
        },
                new String[]{
            "Linha", "Token", "Tipo", "Valor"
        }){
            boolean[] canEdit = new boolean[]{false, false, false, false};
        });
    }//GEN-LAST:event_botãoLimparActionPerformed

    private void botaoNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoNovoActionPerformed
        if(!areaCodigo.getText().equals(""))
        {
            int resposta2 = JOptionPane.showConfirmDialog(null, "Deseja salvar a edição do código?",
                    "Novo", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);

            if (resposta2 == JOptionPane.YES_OPTION) {
                this.menuSalvarActionPerformed(evt);
                areaCodigo.setText("");
            }
            else if (resposta2 == JOptionPane.NO_OPTION) {
                areaCodigo.setText("");
            }
    }
         this.areaSaida.setText("");
         tabArquivosTexto.setTitleAt(0, "Novo arquivo");

        //Apaga as linhas da tabela de tokens
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Linha", "Token", "Tipo", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };
        });
    }//GEN-LAST:event_botaoNovoActionPerformed

    private void arquivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_arquivoActionPerformed
        if(!areaCodigo.getText().equals(""))
        {
            int resposta2 = JOptionPane.showConfirmDialog(null, "Deseja salvar a edição do código?",
                    "Novo", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);

            if (resposta2 == JOptionPane.YES_OPTION) {
                this.menuSalvarActionPerformed(evt);
                areaCodigo.setText("");
            }
            else if (resposta2 == JOptionPane.NO_OPTION) {
                areaCodigo.setText("");
            }
    }
         this.areaSaida.setText("");
         tabArquivosTexto.setTitleAt(0, "Novo arquivo");

        //Apaga as linhas da tabela de tokens
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Linha", "Token", "Tipo", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };
        });
    }//GEN-LAST:event_arquivoActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaInicial().setVisible(true);
            }
        });
    }

    public void imprimeTabelaTokens(String token, String tipo, String valor, int linha){
        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        String line = null;
        line = String.valueOf(linha);
        String[] dados = {line, token, tipo, valor};
        modelo.addRow(dados);
    }

    public void imprimeErros(String erro){

        areaSaida.append(erro + "\n");
        areaSaida.setForeground(Color.red);

    }

    public void imprimeSucesso(){
        areaSaida.append("Construído com sucesso!");
        areaSaida.setForeground(Color.green);
    }

    public void imprimeTerminado(int erros){
        areaSaida.append("TERMINADO COM " + erros + " ERROS.");
        areaSaida.setForeground(Color.red);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton abortar;
    private javax.swing.JButton abrir;
    private javax.swing.JTextArea areaCodigo;
    private javax.swing.JTextArea areaSaida;
    private javax.swing.JMenu arquivo;
    private javax.swing.JButton botaoCompilar;
    private javax.swing.JButton botaoNovo;
    private javax.swing.JButton botãoAjuda;
    private javax.swing.JButton botãoLimpar;
    private javax.swing.JButton botãoSalvar;
    private javax.swing.JMenu compilar;
    private javax.swing.JMenuItem compilarLexico;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTable jTable1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JMenuItem menuAbortar;
    private javax.swing.JMenuItem menuAbrir;
    private javax.swing.JMenuItem menuAjuda;
    private javax.swing.JMenuItem menuNovo;
    private javax.swing.JMenuItem menuSalvar;
    private javax.swing.JTabbedPane tabArquivosTexto;
    private javax.swing.JTabbedPane tabSaida;
    private javax.swing.JTabbedPane tabTokens;
    private javax.swing.JTable tabelaDeSimbolos;
    // End of variables declaration//GEN-END:variables

}
